let GM = require('GM');
cc.Class({
    extends: cc.Component,

    properties: {
        speed: cc.v2(0, 0),
        addSpeed: 600,
        maxSpeed: cc.v2(10, 1000),
        gravity: -1000,
        jumpSpeed: 400,
        collisionX: 0,
        collisionY: 0,
        direction: 0, //控制的方向，只有左右
        jumping: false, //跳跃
        jumpCount: 0, //跳跃次数
        drag: 2000,
        prePosition: cc.v2(0, 0), //上一帧的坐标
        //player: null, // 动画播放器

        // //外部组件
        // uiLayer: cc.Node,
        // uiLayerComonent: null,

        //角色美术预制件
        roles: [cc.Prefab],
        roleNode: cc.Node,
        _index: 0,
        index: {
            type: cc.Integer,
            get() {
                return this._index;
            },
            set(value) {
                //超出或者等于则不改变
                if (value >= this.roles.length || value == this._index) return;
                this._index = value;
                this.roleNode.children.forEach(item => {
                    item.destroy();
                });

                let node = cc.instantiate(this.roles[value]);
                node.scale = cc.v2(1, 1);
                node.parent = this.roleNode;
            }
        },
        //护盾
        hudun: cc.Node,
        //玩家生命(为0则死亡)
        _playerLife: {
            type: cc.Integer,
            default: 1,
        },
        //玩家生命
        playerLife: {
            type: cc.Integer,
            get() {
                return this._playerLife;
            },
            set(value) {
                //最大值为2
                if (value > 2) value = 2;
                //如果是御剑状态并且会掉血
                if (this.flying && value < this._playerLife) return;
                switch (value) {
                    case 2:
                        this.hudun.active = true;
                        break;
                    case 1:
                        this.hudun.active = false;
                }
                this._playerLife = value;
            }
        },
        //御剑飞行
        flying: 0,

        //满100(御剑飞行能量条)
        _energyFrameCount: {
            type: cc.Integer,
            default: 0,
        },
        energyFrameCount: {
            get() {
                return this._energyFrameCount;
            },
            set(value) {
                if (this.flying) return;
                if (value >= 500) {
                    value = 0;
                    this.fly();
                }
                this._energyFrameCount = value;
                if (this.gameCtrl) {
                    this.gameCtrl.updateFly(this._energyFrameCount);
                }
            }
        },
        game: cc.Node,

        //爆炸特效预制组件
        breakPrefab: cc.Prefab,
        //金币、
        goldPrefab: cc.Prefab,

        //拖尾动画
        tuoweiNode: cc.Node,
        //粒子动画（御剑飞行才有）
        flySprintNode: cc.Node,
        //复活节点
        resurgence: cc.Node,
        //windy
        windys: cc.Node,

    },

    // use this for initialization
    onLoad: function () {
        //console.log(GM.roleIndex);
        this.index = GM.roleIndex;

        this.scheduleOnce(() => {
            this.player = this.roleNode.children[0].getComponent(cc.Animation);
        });

        this.prePosition.x = this.node.x;
        this.prePosition.y = this.node.y;

        //久的碰撞节点（防止连续碰撞多次）
        this.preBoxColl = null;

        var manager = cc.director.getCollisionManager();
        manager.enabled = true;
        //manager.enabledDebugDraw = true;

        //this.player = this.roleNode.children[0].getComponent(cc.Animation);

        //UI组件
        //this.uiLayerComonent = this.uiLayer.getComponent("uiLayer");

        this.gameCtrl = this.game.getComponent('gameCtrl');

        this.boxColl = this.getComponent(cc.BoxCollider);

        //正常大小的碰撞
        this.normalBoxCollSize = cc.size(this.boxColl.size.width, this.boxColl.size.height);
        //偏移
        this.normalBoxCollOffset = cc.v2(this.boxColl.offset.x, this.boxColl.offset.y);

        //爆炸对象池
        this.breaks = new cc.NodePool('breaks');
        //金币对象池
        this.golds = new cc.NodePool('golds');
        let nember = 20;
        for (let i = 0; i < nember; i++) {
           var node = cc.instantiate(this.goldPrefab);
           this.golds.put(cc.instantiate(this.goldPrefab));
            
        }
        //金币分数对象池
        this.goldscore = new cc.NodePool('goldscore');

        window.role = this;
        role.dcs = [];
        this.GM = GM;
    },

    onDestroy: function onDisabled() {
        cc.director.getCollisionManager().enabled = false;
        cc.director.getCollisionManager().enabledDebugDraw = false;
    },

    //跳跃
    JumpFun() {
        //御剑飞行时不能跳跃
        if (this.flying) return;
        if (!this.jumping || this.jumpCount < 2) {
            this.jumping = true;
            this.speed.y = this.jumpSpeed;

            this.jumpCount++;
            this.jumpCount < 2 ? this.player.play("jump") : this.player.play("double_jump");
        }
    },

    //下滑
    SquatFun() {
        //跳跃的时候不能下滑 (御剑飞行时不能下滑)
        if (this.jumping || this.flying) return;
        //缩放或者修改碰撞
        // this.node.scaleY = 0.5;
        // this.roleNode.scaleY *= 2;
        this.boxColl.size.height *= 0.5;
        this.boxColl.offset.y -= this.boxColl.size.height * 0.5;
        this.player.play("squat");
        this.unPlayRunTx();
    },

    //取消下滑
    unSquatFun() {
        //御剑飞行时不能下滑
        if (this.flying) return;
        this.player.play("run");
        this.playRunTx();
        this.boxColl.size.height = this.normalBoxCollSize.height;
        this.boxColl.offset.y = this.normalBoxCollOffset.y;
    },

    //奔跑特效
    playRunTx() {
        this.tuoweiNode.active = true;
    },

    //不奔跑特效
    unPlayRunTx() {
        this.tuoweiNode.active = false;
    },

    //御剑飞行
    fly() {
        this.player.play("fly");
        this.unschedule(this.unFly);
        this.flying = 1;
        GM.flying = 1;
        //放大碰撞范围，清屏
        this.boxColl.size.height = 1000;
        if (this._gameOver == 1) {
            this.scheduleOnce(this.unFly, 5);
        } else {
            //20s后关闭御剑飞行
            this.scheduleOnce(this.unFly, 9);
        }
        this.flySprintNode.active = true;
        this.windys.active = true;
    },

    //关闭御剑飞行
    unFly() {
        this.windys.active = false;
        this.flying = 0;
        GM.flying = 0;
        this.player.play("fall");
        this.flySprintNode.active = false;
        this.boxColl.size.height = this.normalBoxCollSize.height;
        if (this._gameOver == 1) {
            //预加载结算界面
            cc.director.preloadScene('Over', function () {
            });
            //还没复活过
            if (this._resurgence !== 1) {
                this.scheduleOnce(() => {
                    cc.director.pause();
                    this.resurgence.active = true;
                }, 0.3)
            } else {
                cc.director.loadScene('Over');
                //this.GoOver();
                this.gameCtrl.over();
            }

        }
    },
    //分享
    onShare() {
        if (window.sdk) {
            sdk.UserShare({
                success: () => {
                    this.onResurgence();
                },
                fail: () => {

                }
            })
        }
    },
    //观看视频
    onWatch() {
        if (window.sdk) {
            sdk.Resurgence({
                success: () => {
                    this.onResurgence();
                },
                fail: () => {

                }
            })
        }
    },
    //复活
    onResurgence() {
        this._resurgence = 1;
        cc.director.resume();
        //游戏不结束
        this._gameOver = 0;
        this.resurgence.active = false;
        this.fly();
    },
    closeResurgence() {
        cc.director.resume();
        //游戏结束
        this.resurgence.active = false;
        cc.director.loadScene('Over');
        //this.GoOver()
        this.gameCtrl.over();
    },
    GoOver() {
        this.loading.active = true;
        cc.director.preloadScene('Over', function () {
            // cc.loader.onProgress = null;
            //加载完毕
            cc.director.loadScene('Over');
        });
    },

    collisionGoldEnter: function (other, self) {
        //金币分数
        // console.log(this.golds.size());
        // let node = this.golds.get();
        // if (!node) {
        //     node = cc.instantiate(this.goldPrefab);
        // }
        // node.setPosition(cc.v2(other.node.x, other.node.y));
        // node.parent = other.node.parent;
        // //分数特效
        // let an = node.children[0].getComponent(cc.Animation);
        // an.play('hint');
        other.node.active = false;
        
        let newNode = other.node.parent.children[0];
        newNode.active = true;
        let an = newNode.getComponent(cc.Animation);
        an.play('hint');
        // an.on('finished', () => {
        //     this.golds.put(node);
        // });
        // this.uiLayerComonent.addGold();
        this.gameCtrl.addGold();
    },


    collisionPlatformEnter: function (other, self) {

        var selfAabb = self.world.aabb.clone();
        var otherAabb = other.world.aabb;
        var preAabb = self.world.preAabb;

        selfAabb.x = preAabb.x;
        selfAabb.y = preAabb.y;

        //检查X是否发生碰撞
        selfAabb.x = self.world.aabb.x;
        if (cc.Intersection.rectRect(selfAabb, otherAabb)) {
            if (this.speed.x < 0 && selfAabb.xMax > otherAabb.xMax) {
                //this.node.x = otherAabb.xMax;
                this.collisionX = -1;
            } else if (this.speed.x > 0 && selfAabb.xMin < otherAabb.xMin) {
                // this.node.x = otherAabb.xMin - selfAabb.width;
                this.collisionX = 1;
            }
            this.speed.x = 0;
            return;
        }

        //检查Y是否发生碰撞
        selfAabb.y = self.world.aabb.y;
        if (cc.Intersection.rectRect(selfAabb, otherAabb)) {
            if (this.speed.y < 0 && selfAabb.yMax > otherAabb.yMax) {
                //中心点（0.5）防止一直触碰
                this.node.y = otherAabb.yMax - 0;
                this.jumping = false;
                //if(this.player._currentClip.name == 'run'){}
                if (this.player) {
                    this.player.play("run");
                }

                //奔跑开启
                this.playRunTx();
                this.jumpCount = 0;
                this.collisionY = -1;
            } else if (this.speed.y > 0 && selfAabb.yMin < otherAabb.yMin) {
                this.node.y = otherAabb.yMin - selfAabb.height;
                this.collisionY = 1;
            }
            this.speed.y = 0;
        }
    },

    //碰撞回调
    onCollisionEnter: function (other, self) {
        // console.log('on collision enter');
        // cc.log("coll tag = " + other.tag);


        if (other.tag == 1) {
            //死亡了
            // if(this._gameOver == 1){
            //     return;
            // }
            this.collisionGoldEnter(other, self);
        }
        //碰撞地面
        else if (other.tag == 0) {
            if (this.flying || this._gameOver == 1) return;
            this.collisionPlatformEnter(other, self);
        }
        //飞镖（空中障碍物、地面障碍物）
        else if (other.tag == 2) {
            if (this.playerLife > 0 || this.flying) {
                other.node.active = false;

                //爆炸特效
                let breakNode = this.breaks.get();
                if (!breakNode) {
                    breakNode = cc.instantiate(this.breakPrefab);
                }
                breakNode.setPosition(cc.v2(other.node.x, other.node.y));
                breakNode.parent = other.node.parent;
                let breakNodeAn = breakNode.getComponent(cc.Animation);
                breakNodeAn.play('break');
                breakNodeAn.on('finished', () => {
                    this.breaks.put(breakNode);
                });
                //other.node.removeFromParent();
            }

            //死亡了
            if (this._gameOver == 1) {
                return;
            }

            this.dcs.push(other.node);

            //防止连续碰撞同一障碍物
            if (other.node !== this.preBoxColl) {
                this.preBoxColl = other.node;

                this.gameOver();

                //2秒后清空
                this.scheduleOnce(() => {
                    this.preBoxColl = null;
                }, 2);
            }
        }

        else if (other.tag == 3) {
            other.node.active = false;
            this.playerLife++;
        }
    },

    gameOver(death) {
        //必杀
        if (death == 2) {
            this.playerLife = 0;
        }
        this.playerLife--;
        //玩家生命未归0
        if (this.playerLife > 0) return;
        //死亡
        this._gameOver = 1;

        this.GM.start = 2;
        //停止跑
        this.player.stop("run");
        //死亡跳跃
        //this.speed = cc.v2(0,0);
        //this.speed.y = 200;

        this.scheduleOnce(() => {
            this.GM.start = 1;
            //死亡飞行
            this.fly();
        }, 0.5);


    },

    onCollisionStay: function (other, self) {
        // console.log('on collision stay');

        if (other.tag != 0) return;
        if (this.collisionY === -1) {
            var offset = cc.v2(other.world.aabb.x - other.world.preAabb.x, 0);

            // var temp = cc.affineTransformClone(self.world.transform);
            // temp.tx = temp.ty = 0;

            // offset = cc.pointApplyAffineTransform(offset, temp);
            //this.node.x += offset.x;
        }
    },

    /**
     * 当碰撞结束后调用
     * @param  {Collider} other 产生碰撞的另一个碰撞组件
     * @param  {Collider} self  产生碰撞的自身的碰撞组件
     */
    onCollisionExit: function (other, self) {
        //console.log('on collision exit');

        if (other.tag != 0) return;
        this.collisionX = 0;
        this.collisionY = 0;
        this.jumping = true;
        this.jumpCount = 1;

        this.unPlayRunTx();

        //御剑飞行
        if (this.flying) {
            return;
        }

        if (this.speed.y > 0) {
            this.player.play("jump");
        } else {
            this.player.play("fall");
        }
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {

        /**
         * Y轴变化
         *  */
        if (this.collisionY === 0) //没任何碰撞，计算重力
        {
            this.speed.y += this.gravity * 0.02;
            if (Math.abs(this.speed.y) > this.maxSpeed.y) {
                this.speed.y = this.speed.y > 0 ? this.maxSpeed.y : -this.maxSpeed.y;
            }
        }

        //掉出屏幕外
        if (this.node.y <= -100 && this._gameOver != 1) {
            this.gameOver(2);
        }

        //左右有碰撞,X立刻停下
        if (this.speed.x * this.collisionX > 0) {
            this.speed.x = 0;
        }

        this.prePosition.x = this.node.x;
        this.prePosition.y = this.node.y;

        this.speed.x = 100;


        //御剑飞行状态
        if (this.flying) {
            if (this.node.y <= 360) {
                this.node.y += 10
                if (this.node.y >= 360) {
                    this.node.y = 360;
                }
            } else {
                this.node.y -= 10
                if (this.node.y <= 360) {
                    this.node.y = 361;
                }
            }
            if (this.node.x <= 760) {
                this.node.x += 3
                if (this.node.x >= 760) {
                    this.node.x = 760;
                }
            } else {
                this.node.x -= 3
                if (this.node.x < 760) {
                    this.node.x = 761;
                }
            }
        } else {
            if (this.node.x >= 350) {
                this.node.x -= 2;
                if (this.node.x < 350) {
                    this.node.x = 350;
                }
            } else {
                this.node.x += 2;
                if (this.node.x >= 350) {
                    this.node.x = 351;
                }
            }
            this.node.x += 0;
            this.node.y += this.speed.y * dt;
        }
    },
});
